from server import db
from sqlalchemy import Column, func, DateTime
from sqlalchemy.dialects.mysql import BIGINT
from datetime import datetime, date
from decimal import Decimal


class BaseOrm(db.Model):
    __abstract__ = True
    id = Column(BIGINT(20, unsigned=True), autoincrement=True, nullable=False, primary_key=True, comment="id")
    create_time = Column(DateTime, nullable=False, server_default=func.now(), comment="创建时间")
    update_time = Column(DateTime, onupdate=func.now(), comment="修改时间 ")

    def to_dict(self, include=None, exclude=None):
        result = {}
        for k in self.__table__.columns.keys():
            if include and k not in include:
                continue
            if exclude and k in exclude:
                continue
            value = getattr(self, k)
            if isinstance(value, datetime) or isinstance(value, date) or isinstance(value, Decimal):
                value = str(value)
            result[k] = value

        return result


def set_field(obj_db, data, include=None, exclude=None):
    for key in obj_db.__table__.columns.keys():
        if include and key not in include:
            continue
        if exclude and key in exclude:
            continue
        if key in data:
            setattr(obj_db, key, data[key])


def query_by_field(query, filter_json, model):
    if getattr(model, 'id'):
        query = query.order_by(model.id.desc())
    if not filter_json:
        return query
    import json
    query_filter = json.loads(filter_json)
    for k, v in query_filter.items():
        if v is None:
            continue
        if isinstance(v, dict):
            if "from" in v:
                query = query.filter(getattr(model, k) >= v.get("from"))
            if "to" in v:
                query = query.filter(getattr(model, k) <= v.get("to"))
            continue
        if isinstance(v, list):
            query = query.filter(getattr(model, k).in_(v))
            continue

        query = query.filter(getattr(model, k) == v)
    return query
